package model;

import org.jblas.DoubleMatrix;

import util.Params;
import util.RandomMatrix;

/**
 * 
 * Convolution Layer.
 * 
 * 卷积网络层。
 * 
 * @author Tianyu Xu
 * 
 */
public class ConvolutionLayer {
	private final int WINDOW_VECTOR_SIZE = Params.WINDOW_SIZE * Params.FEATURE_VECTOR_SIZE;

	public DoubleMatrix W = null;
	private DoubleMatrix bias = null;

	public ConvolutionLayer() {
		// initialize the weight matrix W and the bias vector
		// 初始化权重矩阵W和偏置向量bias
		W = RandomMatrix.rand(Params.CONVOLITION_LAYER_SIZE, WINDOW_VECTOR_SIZE);
		bias = RandomMatrix.rand(Params.CONVOLITION_LAYER_SIZE);
	}

	public DoubleMatrix performConvolutionTrans(DoubleMatrix inputMatrix) {
		final int SEN_LENGTH = inputMatrix.columns - Params.WINDOW_SIZE + 1;
		DoubleMatrix output = new DoubleMatrix(Params.CONVOLITION_LAYER_SIZE, SEN_LENGTH);

		// for each word in the sentence (without paddings)
		// 对句子（不含左右填充）中的每个字进行遍历
		for (int i = 0; i < SEN_LENGTH; i++) {
			// construct window vector
			// 构造窗口向量
			DoubleMatrix windowVector = new DoubleMatrix(0, 1);
			for (int k = 0; k < Params.WINDOW_SIZE; k++) {
				windowVector = DoubleMatrix.concatVertically(windowVector, inputMatrix.getColumn(i + k));
			}
			output.putColumn(i, W.mmul(windowVector));
		}
		output.addColumnVector(bias);
		return output;
	}

	public DoubleMatrix getW() {
		return W;
	}

	public DoubleMatrix getBias() {
		return bias;
	}
}
